import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import './Payment.css';
import axios from 'axios';
import Layout from './Layout';

interface PaymentInfo {
    name: string;
    orderNo: string;
    totalAmount: number;
    merchantNo: string;
    productType: string;
    region: string;
    requestTime: string;
}

const Payment = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const payRef = useRef<HTMLDivElement>(null);
    const [paymentInfo, setPaymentInfo] = useState<PaymentInfo>({
        name: '',
        orderNo: '',
        totalAmount: 0,
        merchantNo: '',
        productType: '',
        region: '',
        requestTime: ''
    });
    const [selectedPayment, setSelectedPayment] = useState('alipay');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        try {
            const orders = JSON.parse(localStorage.getItem('orders') || '{}');
            if (orders && orders[0] && orders[0].items && orders[0].items[0]) {
                setPaymentInfo({
                    name: orders[0].items[0].name,
                    orderNo: `OD${Date.now()}`,
                    totalAmount: orders[0].total || 0,
                    merchantNo: '010156112100001',
                    productType: '100011',
                    region: '156',
                    requestTime: new Date().toISOString().replace(/[-:]/g, '').split('.')[0]
                });
            } else {
                setError('订单信息不完整');
                navigate('/cart');
            }
        } catch (err) {
            setError('加载订单信息失败');
            console.error('Error loading order info:', err);
            navigate('/cart');
        }
    }, [navigate]);

    const handlePaymentSubmit = useCallback(async () => {
        if (loading) return;

        setLoading(true);
        setError(null);

        try {
            const response = await axios.post("http://localhost:5000/pay", {
                orderNumber: paymentInfo.orderNo,
                amount: paymentInfo.totalAmount,
                goodsInfo: paymentInfo.name
            });

            if (payRef.current) {
                payRef.current.innerHTML = response.data;
            }

            // 更新订单状态
            const orders = JSON.parse(sessionStorage.getItem('orders') || '[]');
            const currentOrderId = sessionStorage.getItem('currentOrderId');

            const updatedOrders = orders.map((order: any) => {
                if (order.id === currentOrderId) {
                    return {
                        ...order,
                        status: '待发货',
                        paymentTime: new Date().toISOString(),
                        paymentMethod: selectedPayment
                    };
                }
                return order;
            });

            // 更新存储的订单数据
            sessionStorage.setItem('orders', JSON.stringify(updatedOrders));
            localStorage.setItem('orders', JSON.stringify(updatedOrders));

            // 清除当前订单ID
            sessionStorage.removeItem('currentOrderId');

            document.forms[0].submit();
        } catch (err) {
            setError('支付失败，请稍后重试');
            console.error('Payment error:', err);
        } finally {
            setLoading(false);
        }
    }, [loading, paymentInfo, navigate, selectedPayment]);

    const handlePaymentMethodChange = useCallback((method: string) => {
        setSelectedPayment(method);
    }, []);

    const handleCancel = useCallback(() => {
        navigate('/order-confirm');
    }, [navigate]);

    if (error) {
        return (
            <div className="payment-error">
                <p>{error}</p>
                <button onClick={() => navigate('/cart')}>返回购物车</button>
            </div>
        );
    }

    return (
        <Layout>
            <div className="payment-page">
                <div ref={payRef}></div>
                <div className="payment-container">
                    <div className="payment-header">
                        <h2>收银台</h2>
                        <div className="order-info">
                            <span>订单号：{paymentInfo.orderNo}</span>
                            <span className="amount">¥{paymentInfo.totalAmount}</span>
                        </div>
                    </div>

                    <div className="payment-methods">
                        <h3>选择支付方式</h3>
                        <div className="payment-options">
                            {[
                                { id: 'alipay', name: '支付宝', icon: '../imgs/支付宝支付.png' },
                                { id: 'wechat', name: '微信支付', icon: '../imgs/微信支付.png' },
                                { id: 'unionpay', name: '银联支付', icon: '../imgs/支付-银联支付.png' }
                            ].map(method => (
                                <label
                                    key={method.id}
                                    className={`payment-option ${selectedPayment === method.id ? 'selected' : ''}`}
                                >
                                    <input
                                        type="radio"
                                        name="payment"
                                        value={method.id}
                                        checked={selectedPayment === method.id}
                                        onChange={() => handlePaymentMethodChange(method.id)}
                                    />
                                    <img src={method.icon} alt={method.name} />
                                    <span>{method.name}</span>
                                </label>
                            ))}
                        </div>
                    </div>

                    <div className="payment-action">
                        <button
                            className="pay-button"
                            onClick={handlePaymentSubmit}
                            disabled={loading}
                        >
                            {loading ? '支付中...' : '立即支付'}
                        </button>
                        <button
                            className="cancel-button"
                            onClick={handleCancel}
                            disabled={loading}
                        >
                            取消支付
                        </button>
                    </div>

                    <div className="payment-notice">
                        <h4>支付说明</h4>
                        <ul>
                            <li>请在24小时内完成支付，超时订单将自动取消</li>
                            <li>如遇支付问题，请联系客服：950801</li>
                            <li>支付完成后，请勿关闭页面，等待系统自动跳转</li>
                        </ul>
                    </div>
                </div>
            </div>
        </Layout>
    );
};

export default Payment; 